package com.pucong.gitee.database.backup.business.websocket;

import com.pucong.gitee.database.backup.business.database.service.OperationDataSqlService;
import com.pucong.gitee.database.backup.utils.ApplicationContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;


@Slf4j
@ServerEndpoint(value = "/websocket/sql")
@Component
public class WebSocketSql {

    private OperationDataSqlService operationDataSqlService;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        log.info("用户:{},连接WebSSH", session.getId());
        getBean();
        //调用初始化连接
        operationDataSqlService.initConnection(session);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        log.info("有一连接关闭：{}", session.getId());
        getBean();
        //调用service关闭连接
        operationDataSqlService.close(session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户:{},发送命令:{}", session.getId());
        getBean();
        //调用service接收消息
        operationDataSqlService.doMsg(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误", error);
    }

    private void getBean(){
        if(operationDataSqlService == null){
            operationDataSqlService = (OperationDataSqlService)ApplicationContextUtil.getBean(OperationDataSqlService.class);
        }
    }
}
